import axios, {AxiosRequestConfig} from "axios";
import {message} from "antd";
import _ from "lodash";
import {IResponse} from "@/common/common";

axios.defaults.validateStatus = () => true;
axios.defaults.timeout = 20000;

const whitelist = ["/login", "/logout"];

export interface RequestConfig extends AxiosRequestConfig {
  useCache?: boolean;
  ignoreAuth?: boolean;
  token?: string;
}

function checkData(json: any) {
  return json || {code: -1};
}

function checkStatus(result: any) {
  return new Promise<IResponse>((resolve, reject) => {
    // console.log(result)
    if (result.status === 200) {
      const json = result.data
      const code = json.code;
      if (code === 401 || code === 403) {
        message.info("您的登录信息已经失效，将会跳转到登录页面...");
        resolve(json);
      } else {
        if (code <= 400) {
          resolve(json);
        } else if (code === 500) {
          message.error(json.message);
        } else {
          resolve(json);
        }
      }
    } else {
      message.error(result.status + ": " + result.statusText);
      resolve({
        code: result.status,
        message: result.statusText,
      });
    }
  });
}

export default (config: RequestConfig, useMock?: boolean) => {
  config.baseURL = '/qk/app'
  return axios(config)
    .then(checkStatus)
    .then(checkData)
    .catch((err) => err);
}

